package com.vshop.controller.order;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.vshop.entity.comentity.UserNoCardOrder;
import com.vshop.entity.comentity.UserOrderPackage;
import com.vshop.entity.comentity.UserOrderPayment;
import com.vshop.entity.interfacerequest.ExceptionRequest;
import com.vshop.entity.interfacerequest.usernocardorder.request.*;
import com.vshop.entity.interfacerequest.usernocardorder.response.ResponseUserNoCardOrder;
import com.vshop.entity.interfacerequest.usernocardorder.response.ResponseUserNoCardOrderData;
import com.vshop.entity.interfacerequest.usernocardorder.response.ResponseUserNoCardOrderTradeData;
import com.vshop.entity.interfacerequest.usernocardorder.response.ResponseUserNoCardOrderTradeDataOrderList;
import com.vshop.service.*;
import com.vshop.utils.Md5Encrypt;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 用户无卡下单
 *
 * @author lm
 * @date 2019/03/07
 */
@RestController
@Api(description = "用户无卡下单")
@Slf4j
public class UserNoCardOrderController {
    @Autowired
    private SequenceService sequenceService;
    @Autowired
    private UserOrderPackageService userOrderPackagePaymentService;
    @Autowired
    private PartnerPackageService partnerPackageService;
    @Autowired
    private UserOrderPaymentService userOrderPaymentService;
    @Autowired
    private UserNoCardOrderService noCardOrderService;
    @Autowired
    private PartnerInfoService partnerInfoService;


    @CrossOrigin
    @RequestMapping(value = "userNoCardOrder", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "用户无卡下单", response = ResponseUserNoCardOrder.class)
    public String userNoCardOrder(@ApiParam @RequestBody RequestUserNoCardOrder request) {
        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());
        //3,定义要回复的内容
        String jsonString;
        ExceptionRequest utils = new ExceptionRequest();
        String requestStr = JSON.toJSONString(request);
        if (requestStr == null) {
            log.info("请求报文不合法:requestStr为空");
            jsonString = utils.dataWeiKong(connSeqNo, curtime);
            return jsonString;
        } else {
            log.info("前端请求报文是：" + requestStr);
            RequestUserNoCardOrder requestPackage = JSONArray.parseObject(requestStr, RequestUserNoCardOrder.class);
            String requestSign = requestPackage.getSign();
            if (requestPackage.getSign() == null) {
                log.info("请求报文不合法:sign为空");
                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                return jsonString;
            } else {
                log.info("请求的签名是：" + requestSign);
                RequestUserNoCardOrderData requestData = requestPackage.getData();
                if (requestPackage.getData() == null) {
                    log.info("请求报文不合法:data为空");
                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                    return jsonString;
                } else {
                    String ConnSeqNo = requestData.getConnSeqNo();
                    String partnerCode = requestData.getPartnerCode();
                    String partnerName = partnerInfoService.getPartnerNameByCode(partnerCode);
                    String tradeTime = requestData.getTradeTime();
                    String tradeType = requestData.getTradeType();
                    String lang = requestData.getLang();
                    String version = requestData.getVersion();

                    RequestUserNoCardOrderTradeData requestTradeData = requestData.getTradeData();

                    if (StringUtils.isBlank(ConnSeqNo) || StringUtils.isBlank(partnerCode) || StringUtils.isBlank(tradeTime) || StringUtils.isBlank(tradeType) || lang == null || version == null || requestTradeData == null) {
                        log.info("请求报文不合法:data参数不合法");
                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                        return jsonString;
                    } else {
                        // 将请求体json转成String
                        String str = JSON.toJSONString(requestData);
                        // 将Str拿去计算签名
                        String sign = utils.calculateSignature(str);
                        log.info("计算的签名是：" + sign);
                        if (!requestSign.equalsIgnoreCase(sign)) {
                            log.info("签名验证失败！");
                            jsonString = utils.signatureFailure(ConnSeqNo, tradeTime, tradeType, "0001", "签名有误，请确认签名！");
                            return jsonString;
                        } else {//签名验证通过
                            log.info("签名通过");
                            String partnerScope = requestTradeData.getPartnerScope();
                            String payAmount = requestTradeData.getPayAmount();
                            String payCurrency = requestTradeData.getPayCurrency();
                            String payId = requestTradeData.getPayId();
                            String iccId = requestTradeData.getIccId();
                            String requestOrderId = requestTradeData.getRequestOrderId();
                            List<RequestUserNoCardOrderTradeDataDeviceList> requestDeviceList = null;

                            String packageCode = "";
                            String packageType = "";
                            String globalOrder = "";
                            String orderPeriod = "";

                            String packageFee = "";
                            String expressFee = "";
                            String cardFee = "";
                            String orderNo = "";

                            if (StringUtils.isBlank(partnerScope) || StringUtils.isBlank(payAmount) || StringUtils.isBlank(payCurrency) || StringUtils.isBlank(payId)) {
                                log.info("请求报文不合法:tradeData参数不合法");
                                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                                return jsonString;
                            } else {
                                requestDeviceList = requestTradeData.getDeviceList();
                                if (requestDeviceList == null) {
                                    log.info("请求报文不合法:deviceList参数不合法");
                                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                                    return jsonString;
                                } else {

                                    List<ResponseUserNoCardOrderTradeDataOrderList> responseOrderList = new ArrayList<ResponseUserNoCardOrderTradeDataOrderList>();
                                    ResponseUserNoCardOrderTradeDataOrderList orderList = null;
                                    ResponseUserNoCardOrderTradeData tradeData = null;

                                    for (RequestUserNoCardOrderTradeDataDeviceList device : requestDeviceList) {

                                        String recipientName = device.getRecipientName();
                                        String recipientPhone = device.getRecipientPhone();
                                        String recipientAddress = device.getRecipientAddress();
                                        String recipientCompany = device.getRecipientCompany();
                                        String recipientEmail = device.getRecipientEmail();
                                        String expressType = device.getExpressType();
                                        String deviceCode = device.getDeviceCode();
                                        String deviceNo = device.getDeviceCode();

                                        List<RequestUserNoCardOrderTradeDataOrderList> requestOrderList = device.getOrderList();

                                        if (requestOrderList == null || StringUtils.isBlank(deviceCode) || StringUtils.isBlank(recipientName) || StringUtils.isBlank(recipientPhone) || StringUtils.isBlank(recipientAddress) ||
                                                StringUtils.isBlank(recipientCompany) || StringUtils.isBlank(recipientEmail) || StringUtils.isBlank(expressType)) {

                                            log.info("请求报文不合法:deviceList参数不合法");
                                            jsonString = utils.dataWeiKong(connSeqNo, curtime);
                                            return jsonString;

                                        } else {
                                            for (RequestUserNoCardOrderTradeDataOrderList list : requestOrderList) {
                                                //生成一个临时的订单号
                                                String tempOrderId = sequenceService.getTempOrderIdTaskNo();
                                                packageCode = list.getPackageCode();
                                                packageType = list.getPackageType();
                                                globalOrder = list.getGlobalOrder();
                                                orderPeriod = list.getOrderPeriod();
                                                orderNo = list.getOrderNo();
                                                packageFee = list.getPackageFee();
                                                expressFee = list.getExpressFee();
                                                cardFee = list.getCardFee();

                                                if (StringUtils.isBlank(packageCode) || StringUtils.isBlank(packageType) || StringUtils.isBlank(globalOrder) || StringUtils.isBlank(orderPeriod) || StringUtils.isBlank(orderNo) || StringUtils.isBlank(packageFee)) {
                                                    log.info("请求报文不合法:OrderList参数不合法");
                                                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                                                    return jsonString;

                                                } else {
                                                    //根据packageCode和partnerCode去查询相应信息
                                                    String name = partnerPackageService.queryPackageNameByCode(packageCode, partnerCode);
                                                    String buyType = partnerPackageService.queryBuyType(packageCode, partnerCode);
                                                    String priceType = partnerPackageService.queryPriceType(packageCode, partnerCode);
                                                    String salesType = partnerPackageService.querySalesType(packageCode, partnerCode);

                                                    if (StringUtils.isBlank(name)) {

                                                        log.info("请求报文中packageCode和partnerCode不匹配");
                                                        jsonString = utils.unmatchPartnerCode(ConnSeqNo, partnerCode, curtime, tradeType);
                                                        return jsonString;

                                                    } else {
                                                        int count = userOrderPackagePaymentService.getOrderListByPackageInfoNoCard(partnerCode, packageCode, name, packageType, globalOrder, orderPeriod, payAmount, payCurrency, partnerScope, orderNo);
                                                        if (count <= 0) {
                                                            log.info("数据库没有这条记录：入库！");

                                                            UserOrderPackage order = new UserOrderPackage();
                                                            order.setDeviceNo(deviceNo);
                                                            order.setDeviceCode(deviceCode);
                                                            order.setIccId(iccId);
                                                            order.setPartnerCode(partnerCode);
                                                            order.setPartnerName(partnerName);
                                                            order.setPackageCode(packageCode);
                                                            order.setPackageName(name);
                                                            order.setPackageType(packageType);
                                                            order.setBuyType(buyType);
                                                            order.setPriceType(priceType);
                                                            order.setSalesType(salesType);
                                                            order.setGlobalOrder("0");
                                                            order.setOrderPeriod(orderPeriod);
                                                            order.setOrderNo(orderNo);
                                                            order.setPayId(payId);
                                                            order.setPayAmount(payAmount);
                                                            order.setPayCurrency(payCurrency);
                                                            order.setPartnerScope(partnerScope);
                                                            order.setRequestOrderId(requestOrderId);
                                                            order.setTempOrderId(tempOrderId);
                                                            order.setIsRenew("0");
                                                            order.setPackageFee(packageFee);
                                                            order.setExpressFee(expressFee);
                                                            order.setCardFee(cardFee);
                                                            order.setOrderStatus("1");
                                                            userOrderPackagePaymentService.insertUserNoCard(order);

                                                            //无卡的实体入库
                                                            UserNoCardOrder noCardOrder = new UserNoCardOrder();
                                                            noCardOrder.setPartnerCode(partnerCode);
                                                            noCardOrder.setPackageCode(packageCode);
                                                            noCardOrder.setDeviceNo(deviceNo);
                                                            noCardOrder.setDeviceCode(deviceCode);
                                                            noCardOrder.setIccId(iccId);
                                                            noCardOrder.setTempOrderId(tempOrderId);
                                                            noCardOrder.setPayId(payId);
                                                            noCardOrder.setRecipientName(recipientName);
                                                            noCardOrder.setRecipientPhone(recipientPhone);
                                                            noCardOrder.setRecipientAddress(recipientAddress);
                                                            noCardOrder.setRecipientCompany(recipientCompany);
                                                            noCardOrder.setRecipientEmail(recipientEmail);
                                                            noCardOrder.setExpressType(expressType);
                                                            //默认是1的状态，就是待发货
                                                            noCardOrder.setOrderStatus("1");
                                                            noCardOrderService.insertNoCardRecord(noCardOrder);
                                                            log.info("下单入库完成");
                                                            //2,将临时的订单号下发回去
                                                            orderList = new ResponseUserNoCardOrderTradeDataOrderList();
                                                            orderList.setOrderNo(orderNo);
                                                            orderList.setTempOrderId(tempOrderId);
                                                            responseOrderList.add(orderList);

                                                            tradeData = new ResponseUserNoCardOrderTradeData();
                                                            tradeData.setPayId(payId);
                                                            tradeData.setOrderList(responseOrderList);


                                                        } else {
                                                            log.info("重复请求");
                                                            if (lang.equals("cn") || StringUtils.isNotBlank(lang)) {
                                                                jsonString = utils.repeatRequest(ConnSeqNo, curtime, tradeType, partnerCode);
                                                                return jsonString;
                                                            } else {
                                                                jsonString = utils.repeatRequestEN(ConnSeqNo, curtime, tradeType, partnerCode);
                                                                return jsonString;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    int count = userOrderPaymentService.findCountById(partnerCode, requestOrderId, payId, payAmount, payCurrency);
                                    if (count <= 0) {
                                        //支付订单表入库
                                        UserOrderPayment payment = new UserOrderPayment();
                                        payment.setPartnerCode(partnerCode);
                                        payment.setRequestOrderId(requestOrderId);
                                        payment.setPayId(payId);
                                        payment.setPayAmount(payAmount);
                                        payment.setPayCurrency(payCurrency);
                                        userOrderPaymentService.insertPaymentUserNoCard(payment);
                                    }
                                    //循环结束
                                    ResponseUserNoCardOrderData data = new ResponseUserNoCardOrderData();
                                    data.setConnSeqNo(ConnSeqNo);
                                    data.setPartnerCode(partnerCode);
                                    data.setTradeType(tradeType);
                                    data.setTradeTime(curtime);
                                    data.setTradeRstCode("0000");
                                    data.setTradeData(tradeData);
                                    if (lang.equals("cn") || StringUtils.isNotBlank(lang)) {
                                        data.setTradeRstMessage("成功");
                                    } else {
                                        data.setTradeRstMessage("success");
                                    }

                                    ResponseUserNoCardOrder responseUserNoCardOrder = new ResponseUserNoCardOrder();
                                    responseUserNoCardOrder.setData(data);
                                    responseUserNoCardOrder.setSign(Md5Encrypt.md5(JSON.toJSONString(data)));

                                    jsonString = JSON.toJSONString(responseUserNoCardOrder);
                                    log.info("响应报文：" + jsonString);
                                    return jsonString;

                                }
                            }
                        }
                    }
                }
            }
        }
    }
}